package sort;

/**
 * 计数排序
 */
public class CountingSort {

    private static void sort(int[] arrSrc) {

        int iMaxValue = 0;
        for (int i = 0; i < arrSrc.length; i++) {
            if (arrSrc[i] > iMaxValue) {
                iMaxValue = arrSrc[i];
            }
        }

        int[] arrTemp = new int[iMaxValue + 1];
        for (int i = 0; i < arrSrc.length; i++) {
            arrTemp[arrSrc[i]]++;
        }

        for (int i = 0; i < arrTemp.length - 1; i++) {
            arrTemp[i + 1] = arrTemp[i + 1] + arrTemp[i];
        }

        int[] arrResult = new int[arrSrc.length];
        for (int i = arrSrc.length - 1; i >= 0; i--) {
            int iIndex = arrTemp[arrSrc[i]] - 1;
            arrResult[iIndex] = arrSrc[i];
            arrTemp[arrSrc[i]]--;
        }

        for (int i = 0; i < arrResult.length; i++) {
            arrSrc[i] = arrResult[i];
        }
    }

    public static void main(String[] args) {
        int[] arrSrc = CommonUtil.createIntArray(20);
        CommonUtil.printArr(arrSrc);
        sort(arrSrc);
        CommonUtil.printArr(arrSrc);
    }
}
